// Thread.hpp
#pragma once

#include <iostream>
#include <string>
#include <ctime>
#include <pthread.h>

// #include <functional>
// using fun = std::function<void()>;
// typedef std::function<void()> fun;


template <class T>
class Thread
{
    typedef void* (*callback_t)(T*, void *);

public:
    static void *Routine(void *args)
    {
        Thread *thread = static_cast<Thread *>(args);
        thread->Entery();
        return nullptr;
    }

public:
    Thread(){}
    Thread(callback_t cb, T *parameter, void *cbthis)
        : _tid(0), _start_timestamp(0), _isrunning(false), _cb(cb), _parameter(parameter), _cbthis(cbthis)
    {
        // if (_parameter) _name = _parameter->name;
    }
    void Run()
    {
        _start_timestamp = time(nullptr);
        _isrunning = true;
        pthread_create(&_tid, nullptr, Routine, this);
    }
    void Join()
    {
        pthread_join(_tid, nullptr);
        _isrunning = false;
    }
    uint64_t StartTimestamp()
    {
        return _start_timestamp;
    }
    bool IsRunning()
    {
        return _isrunning;
    }
    void Entery()
    {
        _cb(_parameter, _cbthis);
    }
    // pthread_t GetTid()
    // {
    //     return _tid;
    // }
    // std::string GetName()
    // {
    //     return _name;
    // }
    ~Thread()
    {
    }

private:
    pthread_t _tid;
    std::string _name;
    uint64_t _start_timestamp; // 时间戳，记录线程启动时间
    bool _isrunning;           // 线程是否是运行的

    callback_t _cb;
    T *_parameter;
    void *_cbthis;
};
